from django.http import JsonResponse
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from django.shortcuts import render, redirect
from app01.utils.script.response import BaseResponse
from django.core.handlers.wsgi import WSGIRequest

class UserInfo(object):
    def __init__(self,role,name,id):
        self.role = role
        self.name = name
        self.id = id
        self.menu_name = None
        self.text_list = []


class AuthMiddleware(MiddlewareMixin):

    def is_white_url(self,request):
        if request.path_info in settings.WHITE_URLS:
            return True
    def process_request(self, request):
        if self.is_white_url(request):
            return
        user_dict = request.session.get(settings.SESSION_KEY)
        if not user_dict:
            return redirect('/login/')
        else:
            request.user = UserInfo(**user_dict)


    def process_view(self, request, callback, callback_args, callback_kwargs):

        if self.is_white_url(request):
            return
        current_name = request.resolver_match.url_name
        # print(current_name)
        if current_name in settings.PERMISSION_PUBLIC:
            return
        user_permisssion_dict = settings.PERMISSION[request.user.role]

        if current_name not in user_permisssion_dict:
            if request.is_ajax:
                res = BaseResponse(detail="没有权限")
                return JsonResponse(res.dict)
            else:
                return render(request,"permission.html")

        #获取权限成功
        text_list = []
        text_list.append(user_permisssion_dict[current_name]["text"])
        menu_name = current_name
        while user_permisssion_dict[menu_name]["parent"]:
            menu_name = user_permisssion_dict[menu_name]["parent"]
            text_list.append(user_permisssion_dict[menu_name]["text"])
        text_list.append("首页")
        text_list.reverse()
        #路径导航
        request.user.text_list = text_list
        #当前菜单
        request.user.menu_name = menu_name


